package com.bawei.arouter

import android.content.Context
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.tencent.mmkv.MMKV

/**
 * Author: Jason Zhang
 * Date: 2024/4/26
 * Desc: 登录态的拦截器
 */
@Interceptor(priority = 5, name = "路由Token拦截器")
class RouteTokenInterceptor : IInterceptor{

    private lateinit var mContext: Context

    //白名单集合
    private val checkPaths = arrayOf("/activity/detail")

    override fun init(context: Context?) {
        if (context != null){
            mContext = context
        }
    }

    override fun process(postcard: Postcard, callback: InterceptorCallback) {
        try {
            if(checkPaths.contains(postcard.path)){
                checkLoginToken(postcard, callback)
            } else {
                //继续执行跳转的逻辑
                callback.onContinue(postcard)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            callback.onContinue(postcard)
        }
    }

    /**
     * 检查登录态
     */
    private fun checkLoginToken(postcard: Postcard, callback: InterceptorCallback) {
        val token = MMKV.defaultMMKV().decodeString("token", "")
        if(token.isNullOrEmpty()){
            postcard.path = "/activity/login"
            postcard.navigation()
        }else{
            callback.onContinue(postcard)
        }
    }

}